#include "deepseekapi.h"
#include <QFile>
#include <QTextStream>
#include <QSettings>
#include <QMessageBox>
#include <QDebug>
#include <QUrlQuery>

DeepSeekAPI::DeepSeekAPI(QObject *parent)
    : QObject(parent)
{
    networkManager = new QNetworkAccessManager(this);
    connect(networkManager, &QNetworkAccessManager::finished, this, &DeepSeekAPI::handleNetworkReply);
    
    // 使用OpenAI兼容的API端点格式
    // 由于DeepSeek可能提供OpenAI兼容的API，我们使用通用格式
    apiEndpoint = "https://api.deepseek.com/v1/chat/completions";
    
    // 允许用户在设置中修改API端点
    QSettings settings("BMI8", "DeepSeekAPI");
    QString savedEndpoint = settings.value("apiEndpoint").toString();
    if (!savedEndpoint.isEmpty()) {
        apiEndpoint = savedEndpoint;
    }
    
    // 加载API密钥
    loadApiKey();
}

DeepSeekAPI::~DeepSeekAPI()
{
    // 清理资源
}

void DeepSeekAPI::loadApiKey()
{
    // 从配置文件加载API密钥和端点
    QSettings settings("BMI8", "DeepSeekAPI");
    apiKey = settings.value("apiKey").toString();
    apiEndpoint = settings.value("apiEndpoint", "https://api.deepseek.com/v1/chat/completions").toString();
    
    // 如果没有找到API密钥，使用默认值（实际应用中应提示用户输入）
    if (apiKey.isEmpty()) {
        apiKey = "YOUR_DEEPSEEK_API_KEY"; // 默认值，应该由用户替换
    }
}

void DeepSeekAPI::askQuestion(const QString &question)
{
    // 检查API密钥是否已设置
    if (apiKey == "YOUR_DEEPSEEK_API_KEY") {
        emit errorOccurred("请先设置DeepSeek API密钥");
        return;
    }
    
    // 准备请求
    QUrl url(apiEndpoint);
    QNetworkRequest request;
    request.setUrl(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    request.setRawHeader("Authorization", QString("Bearer %1").arg(apiKey).toUtf8());
    
    // 构建请求体
    QJsonObject requestBody;
    requestBody["model"] = "deepseek-chat"; // 使用DeepSeek聊天模型，可能需要根据实际情况调整
    
    // 添加调试日志
    qDebug() << "发送请求到:" << url.toString();
    qDebug() << "使用API密钥:" << apiKey.left(5) + "..."; // 只显示前5个字符，保护密钥安全
    
    QJsonArray messages;
    
    // 系统消息，指导AI回答BMI相关问题
    QJsonObject systemMessage;
    systemMessage["role"] = "system";
    systemMessage["content"] = QString("你是一个专业的健康顾问，专注于BMI（身体质量指数）相关问题。"
                              "请提供准确、科学的BMI相关信息，包括计算方法、健康标准、改善建议等。"
                              "回答要简洁明了，专业可靠，并基于最新的医学研究。");
    messages.append(systemMessage);
    
    // 用户问题
    QJsonObject userMessage;
    userMessage["role"] = "user";
    userMessage["content"] = question;
    messages.append(userMessage);
    
    requestBody["messages"] = messages;
    requestBody["temperature"] = 0.3; // 较低的温度使回答更加精确
    requestBody["max_tokens"] = 1000; // 限制回答长度
    
    // 发送请求
    QJsonDocument doc(requestBody);
    QByteArray data = doc.toJson();
    networkManager->post(request, data);
}

void DeepSeekAPI::handleNetworkReply(QNetworkReply *reply)
{
    if (reply->error() == QNetworkReply::NoError) {
        // 解析响应
        QByteArray responseData = reply->readAll();
        QJsonDocument jsonResponse = QJsonDocument::fromJson(responseData);
        QJsonObject jsonObject = jsonResponse.object();
        
        // 从响应中提取回答
        if (jsonObject.contains("choices") && jsonObject["choices"].isArray()) {
            QJsonArray choices = jsonObject["choices"].toArray();
            if (!choices.isEmpty() && choices[0].isObject()) {
                QJsonObject choice = choices[0].toObject();
                if (choice.contains("message") && choice["message"].isObject()) {
                    QJsonObject message = choice["message"].toObject();
                    if (message.contains("content") && message["content"].isString()) {
                        QString answer = message["content"].toString();
                        emit responseReceived(answer);
                        reply->deleteLater();
                        return;
                    }
                }
            }
        }
        
        // 如果无法解析回答
        emit errorOccurred("无法解析API响应");
    } else {
        // 处理错误
        QByteArray responseData = reply->readAll();
        qDebug() << "API错误响应:" << responseData;
        qDebug() << "HTTP状态码:" << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
        qDebug() << "错误类型:" << reply->error();
        qDebug() << "错误字符串:" << reply->errorString();
        
        // 尝试解析错误响应
        QString errorMessage = "API请求错误: " + reply->errorString();
        QJsonDocument errorJson = QJsonDocument::fromJson(responseData);
        if (!errorJson.isNull() && errorJson.isObject()) {
            QJsonObject errorObj = errorJson.object();
            if (errorObj.contains("error") && errorObj["error"].isObject()) {
                QJsonObject error = errorObj["error"].toObject();
                if (error.contains("message") && error["message"].isString()) {
                    errorMessage += " - 详细信息: " + error["message"].toString();
                }
            }
        }
        
        emit errorOccurred(errorMessage);
    }
    
    reply->deleteLater();
}